<?php
// ----------------------------------------------------------
// * @Copyright @ 2011-2020 By HuaXiaXinCai
// ----------------------------------------------------------
// * @Author Yang Changwu<800334@qq.com> 2016-12-12
// ----------------------------------------------------------
namespace Controller;
use \GatewayWorker\Lib\Gateway;
use \Controller\Core;

class Shop extends Core{
    //商城列表
    public function Goods($data,$client_id) {
        if(!isset($data['page'])) $data['page'] = 1;
        if(!isset($data['pagesize'])) $data['pagesize'] = 10;
        $shoplist = $this->db->select('*')->from('sz_shop')->where('status=1')->setPaging($data['pagesize'])->page($data['page'])->orderByASC(array('id'),true)->query();
        $count = $this->db->select('count(*) as count')->from('sz_shop')->where('status=1')->row();
        $msg = [
            'method' => 'Goods',
            'count' => $count['count'],
            'page' => $data['page'],
            'data' => $shoplist,
        ];
        self::SendMsg(1001,$msg);
    }
    //商城兑换购买
    public function Pay($data,$client_id) {
        //判断商品存在
        $shopinfo = $this->db->select('*')->from('sz_shop')->where('status=1 and id='.$data['id'])->row();
        if(!$shopinfo){
            return self::SendMsg(1027,array('method'=>'Pay'));
        }
        //判断商品库存
        if($shopinfo['amount'] - $shopinfo['money'] < 0 ){
            return self::SendMsg(1028,array('method'=>'Pay'));
        }
        //判断金币
        $user = $this->db->select('gold')->from('sz_user')->where('uid='.$_SESSION['uid'])->row();
        if(($user['gold']-$shopinfo['gold']) < 0){
            return self::SendMsg(1023,array('method'=>'Pay'));
        }
        //处理用户增加前辍问题
        //$_SESSION['username'] = 'zh_18217261301';
        $user = explode('_', $_SESSION['username']);
        $username = empty($user[1]) ? $user[0]:$user[1];
        $_SESSION['username'] = $username;
        
        //向第三方发起请求
        $orderid = date(Ymd).self::RandString(1,4).date(His).self::RandString(1,4).self::RandString(3,1);
        $return = $this->ToGoldBean($shopinfo['money'],$_SESSION['username'],$orderid);
        if((int)$return['Result']['code'] == 1001 && (int)$return['Content']['Msg'] == 1){
            $this->ExchangSuccess($data, $shopinfo, $orderid,$return);
            return self::SendMsg(1001,array('method'=>'Pay','gold'=>$shopinfo['gold'],'id'=>$data['id']));
        }else{
            //失败在重发一次请求
            $return = $this->ToGoldBean($shopinfo['money'],$_SESSION['username'],$orderid);
            if((int)$return['Result']['code'] == 1001 && (int)$return['Content']['Msg'] == 1){
                $this->ExchangSuccess($data, $shopinfo, $orderid,$return);
                return self::SendMsg(1001,array('method'=>'Pay','gold'=>$shopinfo['gold'],'id'=>$data['id']));
            }else{
                return self::SendMsg(1029,array('method'=>'Pay'));
            }
        }
        
    }
    //购买兑换成功处理
    public function ExchangSuccess($data,$shopinfo,$orderid,$return){
        //减掉金币,加上金豆
        $gold = $shopinfo['gold'];
        $money = $shopinfo['money'];
        $sqluser = "UPDATE `sz_user` SET gold = gold-$gold,money=money+$money WHERE uid=".$_SESSION['uid'];
        $this->db->query($sqluser);

        //减掉库存
        $sqlshop = "UPDATE sz_shop SET amount = amount-$money WHERE id=".$data['id'];
        $this->db->query($sqlshop);

        //写入购买记录
        $shoplog = [
            'orderid'   => $orderid,
            'username'  => $_SESSION['username'],
            'money'     => $money,
            'gold'      => $gold,
            'addtime'   => time(),
            'remark'    => json_encode($return),
            'status'    =>1,
        ];
        $shop_log['id'] = $this->db->insert('sz_shop_log')->cols($shoplog)->query();
    }
    //第三方请求接口
    public function ToGoldBean($money,$username,$orderid) {
        //测服api地址：http://211.95.72.98:8088/v2/tuangou/CurrencyToBean
        //我的api地址后面跟上下面7个参数,并按顺序排列
        $userkey="&123456";
        $app_key="cps3721";
        $dvirtualcurrency = $money*45;
        $euid = $username;
        //$euid = 18217261301;
        $format="json";
        $sign_method= "md5";
        $timestamp = date(YmdHis);
        $sign=md5($app_key.$dvirtualcurrency.$euid.$format.$orderid.$sign_method.$timestamp.$userkey);
        //正式地址
        $url = "http://appapi.3721zh.com/v2/tuangou/CurrencyToBean?app_key=$app_key&dvirtualcurrency=$dvirtualcurrency&euid=$euid&format=$format&orderid=$orderid&sign_method=$sign_method&timestamp=$timestamp&sign=$sign";
        //测试地址
        //$url = "http://211.95.72.98:8088/v2/tuangou/CurrencyToBean?app_key=$app_key&dvirtualcurrency=$dvirtualcurrency&euid=$euid&format=$format&orderid=$orderid&sign_method=$sign_method&timestamp=$timestamp&sign=$sign";
        $return = self::get_curl($url);
        //写入日志
        self::WriteLog('pay', $url.'===='.$return);
        $return = json_decode($return,true);
        return $return;
    }
    public function BuDanTo($data,$client_id){
        $orderid = '20161215X165419Q372';
        $money = 50;
        $username = '18521708391';
        $gold = 2250;
        $return = $this->ToGoldBean($money,$username,$orderid);
        if((int)$return['Result']['code'] == 1001 && (int)$return['Content']['Msg'] == 1){
            //写入购买记录
            $shoplog = [
                'orderid'   => $orderid,
                'username'  => $username,
                'money'     => $money,
                'gold'      => $gold,
                'addtime'   => time(),
                'remark'    => json_encode($return),
                'status'    =>1,
            ];
            $shop_log['id'] = $this->db->insert('sz_shop_log')->cols($shoplog)->query();
        }else{
            return self::SendMsg(1029,array('method'=>'Pay'));
        }
        
    }
}